package com.ambow.store.controller;

import com.ambow.store.controller.Exception.FileEmptyException;
import com.ambow.store.controller.Exception.FileSizeException;
import com.ambow.store.controller.Exception.FileStateException;
import com.ambow.store.controller.Exception.FileTypeException;
import com.ambow.store.controller.util.Result;
import com.ambow.store.entity.User;
import com.ambow.store.service.UserService;
import com.ambow.store.service.exception.UserNameRepeatException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("users")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Value("${avatar.path}")
    private String avatarPath;

    @PostMapping("/add")
    public Result add(User user){
        userService.addUser(user);
        return new Result(OK,"添加成功");
    }

    @PostMapping("/login")
    public Result login(User user, HttpSession request){
        User data = userService.userLogin(user);
        //将员工信息存入session
        request.setAttribute("uid",data.getUid());
        request.setAttribute("username",data.getUsername());
        //获取session中绑定的数据
//        System.out.println(getUidFromSession(request));
//        System.out.println(getUserNameFromSession(request));

        return new Result(OK,data);
    }

    @PostMapping("/modify")
    public Result modifyPassword(User user,HttpSession session){
        userService.modifyUserPassword(user,session);
        return new  Result(OK);
    }

    @GetMapping("/getuserinfo")
    public Result getUserInfo(HttpSession session){
        User userData = userService.getUserInfo(session);
        return new Result(OK,userData);
    }

    @PostMapping("modifyuserinfo")
    public Result modifyUserInfo(User user,HttpSession session){
        userService.modifyUserInfo(user,session);
        return new Result(OK);
    }

    //设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;

    //限制上传文件的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }

    /**
     * 当前后端数据不一致时使用RequestParam()指定前端传回的数据
     * @param session
     * @param file
     * @return
     */
    @PostMapping("/modifyavatar")
    public Result modifyAvatar(HttpSession session,@RequestParam("file") MultipartFile file){
        //判断文件是否为null
        if(file.isEmpty()){
            throw new FileEmptyException("文件为空");
        }
        //判断文件是否超出大小
        if (file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件超出限制");
        }
        //判断文件的类型是否是我们规定的后缀类型
        String contentType = file.getContentType();
        //如果集合包含某个元素则返回true
        if (!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("文件类型不支持");
        }
        //file对象指向这个路径，file是否存在
        File dir = new File(avatarPath);
        //当路径不存在时，创建
        if(!dir.exists()){//当目录不存在时
            dir.mkdirs();//创建目录
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用uuid防止文件名重复
        String fileName = UUID.randomUUID().toString().toUpperCase() + suffix;
        String path = avatarPath + fileName;//全路径

        try {
            file.transferTo(new File(path));//将数据写入
        } catch (FileStateException e){
            throw new FileStateException("文件状态异常");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        int uid = (Integer) session.getAttribute("uid");
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUid,uid);
        User result = userService.getOne(userLambdaQueryWrapper);
        result.setModifiedUser((String) session.getAttribute("username"));
        String avatar = "../images/avatar/" + fileName;
        result.setAvatar(avatar);
        userService.modifyUserAvatar(result);
        return new Result(OK,(Object) avatar);
    }

}

























